package com.zhentao.controller;

import com.zhentao.aop.MyLog;
import com.zhentao.constants.Constants;
import com.zhentao.loginUser.pojo.TMenu;
import com.zhentao.pojo.TUser;
import com.zhentao.redis.RedisCacheUtil;
import com.zhentao.result.Result;
import com.zhentao.service.TMenuService;
import com.zhentao.service.TUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("user")
@Slf4j
@Api("TUserController")
public class TUserController {
    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private TMenuService tMenuService;
    @Resource
    private TUserService tUserService;

    /**
     * 每天凌晨12点执行
     * 清除用户的登录状态
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void publishExamination(){
        System.out.println("清空全部用户状态");
        List<TUser> list = tUserService.list();
        for (TUser tUser : list) {
            redisCacheUtil.redisTemplate.delete("user_session:"+tUser.getUserId());
        }
    }

    @GetMapping("/clearStart")
    public Result clearStart(){
        this.publishExamination();
        return Result.OK();
    }
    /**
     * 获取用户信息
     * @param servletRequest
     * @return
     */
    @GetMapping("/userdata")
    @ApiOperation(value = "获取用户信息")
    public Result userdata(ServletRequest servletRequest){
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(Constants.TOKEN);
        TUser user = redisCacheUtil.getCacheObject(token);//获取登录者信息
        log.info("============={}"+user);
        //返回用户权限字符
        return Result.OK(user);
    }

    @GetMapping("/getMenusUrl")
    public Result getMenusUrl(Integer uid){
        ArrayList<TMenu> list = new ArrayList<>();
        List<TMenu> list1 = tUserService.findLoginTMenu(uid);
        for (TMenu tMenu :list1){
            if (tMenu.getUrl()!=null){
                list.add(tMenu);
            }
        }
        return Result.OK(list);
    }

}
